package com.stephen.mymall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.stephen.mymall.entity.User;
import com.stephen.mymall.enums.ResultEnum;
import com.stephen.mymall.exception.ResultException;
import com.stephen.mymall.mapper.UserMapper;
import com.stephen.mymall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


/**
 * @ author: stephen
 * @ create: 2020-03-17 20:24
 * @ description:
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void register(User user) {
        // 先查询username是否存在
        int count = userMapper.selectCount(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (count > 0) { // 用户已存在
            throw new ResultException(ResultEnum.USER_HAS_EXIST);
        }
        // MD5加密
        String encodePsd = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(encodePsd);
        int resultCount = userMapper.insert(user);
        if (resultCount == 0) {
            throw new ResultException(ResultEnum.REGISTER_ERROR);
        }
    }
}
